//
//  GeoViewController.m
//  SearchV3Demo
//
//  Created by songjian on 13-8-14.
//  Copyright (c) 2013年 songjian. All rights reserved.
//

#import "TipViewController.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import <MAMapKit/MAMapKit.h>
#import "Location.h"
#import "CommonUtility.h"
#import "TransviaMapViewController.h"
#import "GaodeAnnoTransViaViewController.h"
#import "TransViaOriginalViewController.h"
//#import "AMapTipAnnotation.h"
//#import "BusStopAnnotation.h"
//#import "POIAnnotation.h"
//#import "BusStopDetailViewController.h"
//#import "PoiDetailViewController.h"
//#import "TipDetailViewController.h"

static const NSInteger RoutePlanningPaddingEdge                    = 20;

@interface TipViewController ()<MAMapViewDelegate, AMapSearchDelegate, UISearchBarDelegate, UISearchResultsUpdating, UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) MAMapView *mapView;
@property (nonatomic, strong) AMapSearchAPI *search;

@property (nonatomic, strong) UISearchController *searchController;
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *tips;
@property (nonatomic, strong) NSMutableArray *busLines;
/* 起始点经纬度. */
@property (nonatomic) CLLocationCoordinate2D startCoordinate;
/* 终点经纬度. */
@property (nonatomic) CLLocationCoordinate2D destinationCoordinate;

/* 用于显示当前路线方案. */
//@property (nonatomic) MANaviRoute * naviRoute;

@property (nonatomic, strong) MAPointAnnotation *startAnnotation;
@property (nonatomic, strong) MAPointAnnotation *destinationAnnotation;


@property (nonatomic, strong) AMapRoute *route;

@property (nonatomic,strong) MAPolyline *polyline;

@end

@implementation TipViewController

#pragma mark - Life Cycle

- (id)init
{
    if (self = [super init])
    {
        self.tips = [NSMutableArray array];
        self.busLines = [NSMutableArray array];
    }
    
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Back"
                                                                             style:UIBarButtonItemStylePlain
                                                                            target:self
                                                                            action:@selector(returnAction)];
    
//    self.mapView = [[MAMapView alloc] initWithFrame:self.view.bounds];
//    self.mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
//    self.mapView.delegate = self;
//    self.mapView.centerCoordinate=[Location shareLocation].location.coordinate;
//    self.mapView.zoomLevel=13;
//    [self.view addSubview:self.mapView];
    
    self.search = [[AMapSearchAPI alloc] init];
    self.search.delegate = self;
    
    [self initSearchController];
    [self initTableView];
}

- (void)viewDidDisappear:(BOOL)animated
{
     self.searchController.active = NO;
    [super viewDidDisappear:animated];
   
}
-(void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBar.hidden=false;
}

#pragma mark - action handling

- (void)returnAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Utility

-(void)searchRouteWithTip: (AMapTip *)tip{
    
    self.startCoordinate        = [Location shareLocation].location.coordinate;
    self.destinationCoordinate  = CLLocationCoordinate2DMake(tip.location.latitude, tip.location.longitude);
    
    MAPointAnnotation *startAnnotation = [[MAPointAnnotation alloc] init];
    startAnnotation.coordinate = self.startCoordinate;
    startAnnotation.title      = @"起始点";
    startAnnotation.subtitle   = [NSString stringWithFormat:@"{%f, %f}", self.startCoordinate.latitude, self.startCoordinate.longitude];
    self.startAnnotation = startAnnotation;
    
    MAPointAnnotation *destinationAnnotation = [[MAPointAnnotation alloc] init];
    destinationAnnotation.coordinate = self.destinationCoordinate;
    destinationAnnotation.title      =@"终点";
    destinationAnnotation.subtitle   = [NSString stringWithFormat:@"{%f, %f}", self.destinationCoordinate.latitude, self.destinationCoordinate.longitude];
    self.destinationAnnotation = destinationAnnotation;
    
    AMapDrivingRouteSearchRequest *navi = [[AMapDrivingRouteSearchRequest alloc] init];
    
    navi.requireExtension = YES;
//    navi.destinationId = @"BV10001595";
//    navi.destinationtype = @"150500";
    //    navi.strategy = 5;
    /* 出发点. */
    navi.origin = [AMapGeoPoint locationWithLatitude:self.startCoordinate.latitude
                                           longitude:self.startCoordinate.longitude];
    
//    waypoints
    /* 目的地. */
    navi.destination = [AMapGeoPoint locationWithLatitude:self.destinationCoordinate.latitude
                                                longitude:self.destinationCoordinate.longitude];
    
    [self.search AMapDrivingRouteSearch:navi];
}
//路线解析
- (MAPolyline *)polylinesForPath:(AMapPath *)path{
    if (path == nil || path.steps.count == 0){
        return nil;
    }
    NSMutableString *polylineMutableString = [@"" mutableCopy];
    for (AMapStep *step in path.steps) {
        [polylineMutableString appendFormat:@"%@;",step.polyline];
    }
    
    NSUInteger count = 0;
    CLLocationCoordinate2D *coordinates = [self coordinatesForString:polylineMutableString
                                                     coordinateCount:&count
                                                          parseToken:@";"];
    
    MAPolyline *polyline = [MAPolyline polylineWithCoordinates:coordinates count:count];
    
    free(coordinates);
    coordinates = NULL;
    return polyline;
}

//解析经纬度
- (CLLocationCoordinate2D *)coordinatesForString:(NSString *)string
                                 coordinateCount:(NSUInteger *)coordinateCount
                                      parseToken:(NSString *)token{
    if (string == nil){
        return NULL;
    }
    
    if (token == nil){
        token = @",";
    }
    
    NSString *str = @"";
    if (![token isEqualToString:@","]){
        str = [string stringByReplacingOccurrencesOfString:token withString:@","];
    }else{
        str = [NSString stringWithString:string];
    }
    
    NSArray *components = [str componentsSeparatedByString:@","];
    NSUInteger count = [components count] / 2;
    if (coordinateCount != NULL){
        *coordinateCount = count;
    }
    CLLocationCoordinate2D *coordinates = (CLLocationCoordinate2D*)malloc(count * sizeof(CLLocationCoordinate2D));
    
    for (int i = 0; i < count; i++){
        coordinates[i].longitude = [[components objectAtIndex:2 * i]     doubleValue];
        coordinates[i].latitude  = [[components objectAtIndex:2 * i + 1] doubleValue];
    }
    return coordinates;
}
/* 输入提示 搜索.*/
- (void)searchTipsWithKey:(NSString *)key
{
    if (key.length == 0)
    {
        return;
    }
    
    AMapInputTipsSearchRequest *tips = [[AMapInputTipsSearchRequest alloc] init];
    tips.keywords = key;
    tips.city     = [Location shareLocation].regeocode.city;
    //    tips.cityLimit = YES; 是否限制城市
    
    [self.search AMapInputTipsSearch:tips];
}

/* 清除annotations & overlays */
- (void)clear
{
    [self.mapView removeAnnotations:self.mapView.annotations];
    [self.mapView removeOverlays:self.mapView.overlays];
}

- (void)clearAndShowAnnotationWithTip:(AMapTip *)tip
{
    /* 清除annotations & overlays */
    [self clear];
    MAMultiPointItem *item = [[MAMultiPointItem alloc] init];
    double  longitude= tip.location.longitude;
    double latitude = tip.location.latitude;
    NSString * name = tip.name;
    NSString *address=tip.address;
    CLLocationCoordinate2D newCoordinate =CLLocationCoordinate2DMake(latitude,longitude);
    item.coordinate = newCoordinate;
    item.title=name;
    item.subtitle=address;
    
    MAAnnotationView *annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:item reuseIdentifier:@"aa"];
    annotationView.canShowCallout               = YES;
    annotationView.draggable                    = false;
    annotationView.rightCalloutAccessoryView    = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
    annotationView.image=[UIImage imageNamed:@"img_map_marker"];
    
    [self.mapView addAnnotations:@[item]];
//    if (tip.uid != nil && tip.location != nil) /* 可以直接在地图打点  */
//    {
//        AMapTipAnnotation *annotation = [[AMapTipAnnotation alloc] initWithMapTip:tip];
//        [self.mapView addAnnotation:annotation];
//        [self.mapView setCenterCoordinate:annotation.coordinate];
//        [self.mapView selectAnnotation:annotation animated:YES];
//    }
//    else if (tip.uid != nil && tip.location == nil)/* 公交路线，显示出来*/
//    {
//        AMapBusLineIDSearchRequest *request = [[AMapBusLineIDSearchRequest alloc] init];
//        request.city                        = @"北京";
//        request.uid                         = tip.uid;
//        request.requireExtension            = YES;
//
//        [self.search AMapBusLineIDSearch:request];
//    }
//    else if(tip.uid == nil && tip.location == nil)/* 品牌名，进行POI关键字搜索 */
//    {
//        AMapPOIKeywordsSearchRequest *request = [[AMapPOIKeywordsSearchRequest alloc] init];
//
//        request.keywords         = tip.name;
//        request.city             = @"北京";
//        request.requireExtension = YES;
//        [self.search AMapPOIKeywordsSearch:request];
//    }
}

/* 展示公交线路 */
- (void)presentCurrentBusLine
{
//    AMapBusLine *busLine = [self.busLines firstObject];
//
//    if (busLine == nil)
//    {
//        return;
//    }
//
//    NSMutableArray *busStopAnnotations = [NSMutableArray array];
//
//    [busLine.busStops enumerateObjectsUsingBlock:^(AMapBusStop *busStop, NSUInteger idx, BOOL *stop) {
//        BusStopAnnotation *annotation = [[BusStopAnnotation alloc] initWithBusStop:busStop];
//
//        [busStopAnnotations addObject:annotation];
//    }];
//
//    [self.mapView addAnnotations:busStopAnnotations];
//
//    MAPolyline *polyline = [CommonUtility polylineForBusLine:busLine];
//
//    [self.mapView addOverlay:polyline];
//
//    [self.mapView setVisibleMapRect:polyline.boundingMapRect edgePadding:UIEdgeInsetsMake(BusLinePaddingEdge, BusLinePaddingEdge, BusLinePaddingEdge, BusLinePaddingEdge) animated:YES];
}

- (void)gotoDetailForTip:(AMapTip *)tip
{
    if (tip != nil)
    {
//        TipDetailViewController *tipDetailViewController = [[TipDetailViewController alloc] init];
//        tipDetailViewController.tip                      = tip;
//        
//        [self.navigationController pushViewController:tipDetailViewController animated:YES];
    }
}

- (void)gotoDetailForBusStop:(AMapBusStop *)busStop
{
//    if (busStop != nil)
//    {
//        BusStopDetailViewController *busStopDetailViewController = [[BusStopDetailViewController alloc] init];
//        busStopDetailViewController.busStop                      = busStop;
//
//        [self.navigationController pushViewController:busStopDetailViewController animated:YES];
//    }
}

- (void)gotoDetailForPoi:(AMapPOI *)poi
{
//    if (poi != nil)
//    {
//        PoiDetailViewController *detail = [[PoiDetailViewController alloc] init];
//        detail.poi                      = poi;
//
//        [self.navigationController pushViewController:detail animated:YES];
//    }
}

#pragma mark - MAMapViewDelegate

//- (void)mapView:(MAMapView *)mapView annotationView:(MAAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
//{
//    if ([view.annotation isKindOfClass:[AMapTipAnnotation class]])
//    {
//        [self gotoDetailForTip:[(AMapTipAnnotation *)view.annotation tip]];
//    }
//    else if ([view.annotation isKindOfClass:[BusStopAnnotation class]])
//    {
//        [self gotoDetailForBusStop:[(BusStopAnnotation*)view.annotation busStop]];
//    }
//    else if ([view.annotation isKindOfClass:[POIAnnotation class]])
//    {
//        [self gotoDetailForPoi:[(POIAnnotation *)view.annotation poi]];
//    }
//}

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    
    static NSString *pointReuseIndetifier = @"pointReuseIndetifier";
    MAAnnotationView *annotationView = (MAPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndetifier];
    if (annotationView == nil)
    {
        annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndetifier];
    }
    
    annotationView.canShowCallout               = YES;
    annotationView.draggable                    = false;
    annotationView.rightCalloutAccessoryView    = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
    annotationView.image=[UIImage imageNamed:@"img_map_marker"];
    
    return annotationView;
    
//    if ([annotation isKindOfClass:[AMapTipAnnotation class]])
//    {
//        static NSString *tipIdentifier = @"tipIdentifier";
//        
//        MAPinAnnotationView *poiAnnotationView = (MAPinAnnotationView*)[self.mapView dequeueReusableAnnotationViewWithIdentifier:tipIdentifier];
//        if (poiAnnotationView == nil)
//        {
//            poiAnnotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:tipIdentifier];
//        }
//        
//        poiAnnotationView.canShowCallout = YES;
//        poiAnnotationView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
//        
//        return poiAnnotationView;
//    }
//    else if ([annotation isKindOfClass:[BusStopAnnotation class]])
//    {
//        static NSString *busStopIdentifier = @"busStopIdentifier";
//
//        MAPinAnnotationView *poiAnnotationView = (MAPinAnnotationView*)[self.mapView dequeueReusableAnnotationViewWithIdentifier:busStopIdentifier];
//        if (poiAnnotationView == nil)
//        {
//            poiAnnotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation
//                                                                reuseIdentifier:busStopIdentifier];
//        }
//
//        poiAnnotationView.canShowCallout = YES;
//        poiAnnotationView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
//
//        return poiAnnotationView;
//    }
//    else if ([annotation isKindOfClass:[POIAnnotation class]])
//    {
//        static NSString *poiIdentifier = @"poiIdentifier";
//        MAPinAnnotationView *poiAnnotationView = (MAPinAnnotationView*)[self.mapView dequeueReusableAnnotationViewWithIdentifier:poiIdentifier];
//        if (poiAnnotationView == nil)
//        {
//            poiAnnotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:poiIdentifier];
//        }
//
//        poiAnnotationView.canShowCallout = YES;
//        poiAnnotationView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
//
//        return poiAnnotationView;
//    }
//
//    return nil;
}

- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay
{
    if ([overlay isKindOfClass:[MAPolyline class]])
    {
        MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:overlay];
        
        polylineRenderer.lineWidth   = 6.f;
        polylineRenderer.strokeColor = [UIColor blueColor];
        
        return polylineRenderer;
    }
    
    return nil;
}

#pragma mark - AMapSearchDelegate

- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error
{
    NSLog(@"Error: %@ - %@", error, error.description);
}

/* 输入提示回调. */
- (void)onInputTipsSearchDone:(AMapInputTipsSearchRequest *)request response:(AMapInputTipsSearchResponse *)response
{
    if (response.count == 0)
    {
        return;
    }
    
    [self.tips setArray:response.tips];
    [self.tableView reloadData];
}

/* 公交搜索回调. */
- (void)onBusLineSearchDone:(AMapBusLineBaseSearchRequest *)request response:(AMapBusLineSearchResponse *)response
{
    if (response.buslines.count != 0)
    {
        [self.busLines setArray:response.buslines];
        
        [self presentCurrentBusLine];
    }
}

/* POI 搜索回调. */
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response
{
//    [self.mapView removeAnnotations:self.mapView.annotations];
//
//    if (response.pois.count == 0)
//    {
//        return;
//    }
//
//    NSMutableArray *poiAnnotations = [NSMutableArray arrayWithCapacity:response.pois.count];
//
//    [response.pois enumerateObjectsUsingBlock:^(AMapPOI *obj, NSUInteger idx, BOOL *stop) {
//
//        [poiAnnotations addObject:[[POIAnnotation alloc] initWithPOI:obj]];
//
//    }];
//
//    /* 将结果以annotation的形式加载到地图上. */
//    [self.mapView addAnnotations:poiAnnotations];
//
//    /* 如果只有一个结果，设置其为中心点. */
//    if (poiAnnotations.count == 1)
//    {
//        [self.mapView setCenterCoordinate:[poiAnnotations[0] coordinate]];
//    }
//    /* 如果有多个结果, 设置地图使所有的annotation都可见. */
//    else
//    {
//        [self.mapView showAnnotations:poiAnnotations animated:NO];
//    }
}
/* 路径规划搜索回调. */
- (void)onRouteSearchDone:(AMapRouteSearchBaseRequest *)request response:(AMapRouteSearchResponse *)response
{
    if (response.route == nil){
        return;
    }
    
    if (response.count > 0){
        //直接取第一个方案
        AMapPath *path = response.route.paths[0];
        //移除旧折线对象
        [_mapView removeOverlay:_polyline];
        //构造折线对象
        _polyline = [self polylinesForPath:path];
        //添加新的遮盖，然后会触发代理方法(- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay)进行绘制
        [_mapView addOverlay:_polyline];
        /* 缩放地图使其适应polylines的展示. */
        [self.mapView setVisibleMapRect:[CommonUtility mapRectForOverlays:@[_polyline]]
                            edgePadding:UIEdgeInsetsMake(RoutePlanningPaddingEdge, RoutePlanningPaddingEdge, RoutePlanningPaddingEdge, RoutePlanningPaddingEdge)
                               animated:YES];
    }
   
}

#pragma mark - UISearchResultsUpdating

- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
    self.tableView.hidden = !searchController.isActive;
    [self searchTipsWithKey:searchController.searchBar.text];
    
    if (searchController.isActive && searchController.searchBar.text.length > 0)
    {
        searchController.searchBar.placeholder = searchController.searchBar.text;
    }
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.tips.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *tipCellIdentifier = @"tipCellIdentifier";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:tipCellIdentifier];
    
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                      reuseIdentifier:tipCellIdentifier];
        cell.imageView.image = [UIImage imageNamed:@"locate"];
    }
    
    AMapTip *tip = self.tips[indexPath.row];
    
    if (tip.location == nil)
    {
        cell.imageView.image = [UIImage imageNamed:@"search"];
    }
    
    cell.textLabel.text = tip.name;
    cell.detailTextLabel.text = tip.address;
    
    return cell;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    AMapTip *tip = self.tips[indexPath.row];
    
//    [self clearAndShowAnnotationWithTip:tip];
//    [self searchRouteWithTip:tip];
//    TransviaMapViewController *tras=[[TransviaMapViewController alloc]init];
//    GaodeAnnoTransViaViewController *tras=[[GaodeAnnoTransViaViewController alloc]init];
    TransViaOriginalViewController *tras=[[TransViaOriginalViewController alloc]init];
    tras.tip=tip;
    [self.navigationController pushViewController:tras animated:YES];
    
    self.searchController.active = NO;
}

#pragma mark - Initialization

- (void)initTableView
{
    //    CGFloat tableY = CGRectGetMaxY(self.navigationController.navigationBar.frame);
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    
    self.tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.hidden = YES;
    
    [self.view addSubview:self.tableView];
}

- (void)initSearchController
{
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    
    self.searchController.searchResultsUpdater = self;
    self.searchController.dimsBackgroundDuringPresentation = NO;
    self.searchController.hidesNavigationBarDuringPresentation = NO;
    
    self.searchController.searchBar.delegate = self;
    self.searchController.searchBar.placeholder = @"请输入关键字";
    [self.searchController.searchBar sizeToFit];
    
    
    self.navigationItem.titleView = self.searchController.searchBar;
}

@end
